package com.hcl.stack;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(3);
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        arrayStack.push(4);

        arrayStack.pop();
        arrayStack.pop();
        arrayStack.pop();
        arrayStack.list();
    }
}

class ArrayStack {
    // 栈大小
    private int maxSize;
    // 数组模拟栈
    private int[] stack;
    // 栈顶
    private int top = -1;

    // 构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    // 判断是否为空
    public boolean isEmpty(){
        // 当栈顶等于-1时为空
        return top == -1;
    }


    // 判断是否满
    public boolean isFull(){
        // 当栈顶 == maxSize-1时满
        return top == maxSize - 1;
    }

    // 添加元素
    public void push(int value){
        if (isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    // 取元素
    public int pop(){
        if (isEmpty()){
            System.out.println();
            throw new RuntimeException("栈空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    // 遍历元素
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
            return;
        }
        // 遍历元素从栈顶开始遍历 反向遍历
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);
        }
    }
}
